package com.sanyou.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mchange.lang.DoubleUtils;
import com.sanyou.mapper.FactoryMapper;
import com.sanyou.pojo.CopperParticleCheckRecord;
import com.sanyou.pojo.Equipment;
import com.sanyou.pojo.Factory;
import com.sanyou.pojo.User;
import com.sanyou.pojo.vo.CopperRtDataVo;
import com.sanyou.pojo.vo.IndustryDataVo;
import com.sanyou.pojo.vo.LifecycleVo;
import com.sanyou.pojo.vo.MaintainDataVo;
import com.sanyou.pojo.vo.ProductCountVo;
import com.sanyou.pojo.vo.ProductVo;
import com.sanyou.pojo.vo.StrippingSpeedAllVo;
import com.sanyou.service.*;
import com.sanyou.utils.JSONResult;
import com.sanyou.utils.PagedResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 客户主页页面相关的接口
 * 该主页所有的接口获取的内容都是基于用户所属车间的，并非基于用户拥有的数据查看权限
 * 即只查询用户所属车间相关的数据
 */
@Api(value = "客户主页面相关的接口",tags = {"客户主页面数据相关的Controller"})
@CrossOrigin
@RestController
@RequestMapping("/client")
public class ClientController {

    @Autowired
    private UserService userService;

    @Autowired
    private IndustryDataService industryDataService;

    @Autowired
    private CopperParticleService copperParticleService;

    @Autowired
    private ProductService productService;

    @Resource
    private FactoryMapper factoryMapper;

    @Autowired
    private FactoryService factoryService;

    @Autowired
    private ClientService clientService;

    /**
     * 根据用户ID分页获取其所属车间在当天时间范围内的动态检测数据
     * @param userId
     * @param page
     * @param pageSize
     * 请求demo:http://localhost:8081/client/lifeCycleManagement?userId=230110DHFKCFPA3C&page=1&pageSize=10
     * @return
     */
    @ApiOperation(value = "阴极板全生命周期管理", notes = "阴极板全生命周期管理")
    @PostMapping("/lifeCycleManagement")
    public JSONResult lifeCycleManagement(String userId,int page,int pageSize){
        User user=userService.getUserById(userId);
        PagedResult result=new PagedResult();int count=0;
        List<LifecycleVo> list=new ArrayList<>();
        //设置当天开始时间
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        //设置当天结束时间
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        if(user!=null){
            //根据用户Id，找出数据库中所有当天的动态检测数据
            PagedResult result1=industryDataService.getLifeCycleData(user.getSubFactoryId(),todayStart.getTime(),todayEnd.getTime(),page,pageSize);
            List<IndustryDataVo> list1=(ArrayList)result1.getRows();
            //对每一条数据遍历，如果缓存里有数据就放入result里
            for (int i=0;i< list1.size();i++){
                LifecycleVo vo=new LifecycleVo();
                vo.setMax(list1.get(i).getMax());
                vo.setPlateno(list1.get(i).getPlateno());
                try{
                    //CopperParticleCheckRecord copperParticleCheckRecord=copperParticleService.getRecordFromCache(list1.get(i).getPlateno());
                    List<CopperParticleCheckRecord> records=copperParticleService.getCopperParticleRecordsOfToday(null,null,list1.get(i).getPlateno(),null);
                    if(records!=null && records.size()>0){
                        CopperParticleCheckRecord copperParticleCheckRecord = records.get(0);
                        vo.setaArea(copperParticleCheckRecord.getaIsOk());
                        vo.setbArea(copperParticleCheckRecord.getbIsOk());
                        list.add(vo);
                        count++;
                    }


                } catch (Exception e){
                    System.out.println(e.getMessage());
                }
//                if (vo.getaArea()!=null||vo.getbArea()!=null)
//                    list.add(vo);count++;
            }
            result.setRows(list);
            result.setPage(page);
            result.setTotal(result1.getTotal());
            result.setRecords(count);
            return JSONResult.ok(result);
    }
        else
            return JSONResult.errorMsg("客户不存在或者客户Id错误!");
    }
    /**
     * 根据用户ID获取其所属车间当天每隔半小时的拨片速度
     * @param userId
     * 请求demo:http://localhost:8081/client/strippingSpeed?userId=230110DHFKCFPA3C
     * @return
     */
    @ApiOperation(value = "机组剥片速度", notes = "机组剥片速度")
    @GetMapping("/strippingSpeed")
    public JSONResult getStrippingSpeed(String userId){
        User user=userService.getUserById(userId);
        if (ObjUtil.isEmpty(user))
            return JSONResult.errorMsg("用户ID非法！");

        return JSONResult.ok(new StrippingSpeedAllVo(
                industryDataService.getStrippingSpeedForClient(userService.getUserById(userId).getSubFactoryId()),
                factoryMapper.selectByPrimaryKey(user.getSubFactoryId()).getFactoryName())
        );
    }
    /**
     * 根据用户ID获取动态监测数据和建议维修阴极板总量分页数据
     * @param userId
     * @param needRepairThreshold
     * @param page
     * @param size
     * 请求demo:http://localhost:8081/client/dynamicDetect?userId=230110DHFKCFPA3C&&needRepairThreshold=5&page=1&size=10
     * @return
     */
    @ApiOperation(value = "动态检测", notes = "动态检测")
    @GetMapping("/dynamicDetect")
    public JSONResult getDynamicDetectPlate(String userId, Double needRepairThreshold, Integer page, Integer size){
        if (StrUtil.isEmpty(userId))
            return JSONResult.errorMsg("用户ID不能为空！");
        if (needRepairThreshold<=0)
            return JSONResult.errorMsg("维修阈值必须为正数！");
        if ( page<=0 || size<=0 )
            return JSONResult.errorMsg("分页参数违法！");

        return JSONResult.ok(industryDataService.getDynamicDetectPlate(userId, needRepairThreshold, page, size));
    }

    /**
     * 根据用户ID获取其所属车间范围下的正处于维修状态下的阴极板信息
     * 请求demo:http://localhost:8081/client/getProductMaintainData?userId=230110DHFKCFPA3C&page=1&pageSize=10
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "获取正在维修的阴极板信息", notes = "根据用户ID获取其所属车间范围下的正处于维修状态下的阴极板信息")
    @GetMapping("/getProductMaintainData")
    public JSONResult getProductMaintainData(String userId, Integer page, Integer pageSize){
        try {
            /**
             * 数据校验
             */
            if (StrUtil.isEmpty(userId))
                throw new Exception("用户ID不能为空！");
            if ( page<=0 || pageSize<=0 )
                throw new Exception("分页参数违法！");

            /**
             * 获取数据
             */
            PagedResult result = clientService.selectProductMaintainDataByUserId(userId,page,pageSize);

            /**
             * 返回查询结果
             */
            return JSONResult.ok(result);
        }catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 查询用户所属车间下所有状态的阴极板数量的统计
     * 请求demo:http://localhost:8081/client/getClientProductCounts?userId=230110DHFKCFPA3C
     * @param userId
     * @return
     */
    @GetMapping("/getClientProductCounts")
    public JSONResult getClientProductCounts(String userId){
        if(StringUtils.isBlank(userId))
            return JSONResult.errorMsg("用户Id为空!");

        //获取用户信息
        User user = userService.getUserById(userId);
        //查询用户所属车间下所有状态的阴极板数量的统计
        ProductCountVo count = productService.getProductCountBySubFactoryId(user.getSubFactoryId());

        //数据转换
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("subFactoryName", count.getFactoryName());//车间名
        jsonObject.put("sum", count.getSum());//总板数
        jsonObject.put("online", count.getOnline());//在线板数
        jsonObject.put("maintain", count.getMaintain());//维修板数
        jsonObject.put("offline", count.getOffline());//备用板数
        jsonObject.put("scrap", count.getScrap());//报废板数
        jsonObject.put("uncodeNum", count.getUncode());//无编码阴极板数量
        jsonObject.put("newAdd", count.getNewAdd());//新增阴极板数量
        jsonObject.put("cycle", factoryService.findById(user.getSubFactoryId()).getEquipCycle());//阴极周期

        return JSONResult.ok(jsonObject);
    }

}
